import React, { useRef, useEffect, useState } from 'react';
import { Card, Typography, Spin } from 'antd';
import { listen } from '@tauri-apps/api/event';
import { invoke } from '@tauri-apps/api/tauri';

interface LogViewerProps {
  logs: string[];
  title?: string;
  height?: number;
  className?: string;
  autoScroll?: boolean;
  realTime?: boolean;
  eventName?: string;
}

const LogViewer: React.FC<LogViewerProps> = ({
  logs,
  title = "日志输出",
  height = 400,
  className = "",
  autoScroll = true,
  realTime = false,
  eventName
}) => {
  const logContainerRef = useRef<HTMLDivElement>(null);
  const [realTimeLogs, setRealTimeLogs] = useState<string[]>([]);
  const [isNearBottom, setIsNearBottom] = useState(true);

  // 合并静态日志和实时日志，限制为最近50行
  const allLogs = realTime ? [...logs, ...realTimeLogs] : logs;
  const displayLogs = allLogs.slice(-50); // 只显示最近50行

  // 监听实时日志事件
  useEffect(() => {
    if (!realTime || !eventName) return;

    const unlisten = listen(eventName, (event: any) => {
      const logMessage = event.payload as string;
      setRealTimeLogs(prev => [...prev, logMessage]);
    });

    return () => {
      unlisten.then(f => f());
    };
  }, [realTime, eventName]);

  // 自动滚动到底部
  useEffect(() => {
    if (autoScroll && logContainerRef.current && isNearBottom) {
      logContainerRef.current.scrollTop = logContainerRef.current.scrollHeight;
    }
  }, [displayLogs, autoScroll, isNearBottom]);

  // 检测滚动位置
  const handleScroll = () => {
    if (logContainerRef.current) {
      const { scrollTop, scrollHeight, clientHeight } = logContainerRef.current;
      const threshold = 50; // 距离底部50px以内认为是接近底部
      setIsNearBottom(scrollHeight - scrollTop - clientHeight < threshold);
    }
  };

  // 滚动到底部
  const scrollToBottom = () => {
    if (logContainerRef.current) {
      logContainerRef.current.scrollTop = logContainerRef.current.scrollHeight;
    }
  };

  return (
    <Card 
      title={
        <div className="flex items-center justify-between">
          <span>{title}</span>
          <span className="text-sm text-gray-400">
            显示最近 {displayLogs.length} 行日志
          </span>
        </div>
      }
      className={`log-viewer ${className}`}
      style={{ background: '#262626' }}
      extra={
        realTime && !isNearBottom && (
          <button
            onClick={scrollToBottom}
            style={{
              background: '#1890ff',
              color: 'white',
              border: 'none',
              borderRadius: '4px',
              padding: '4px 8px',
              fontSize: '12px',
              cursor: 'pointer'
            }}
          >
            滚动到底部
          </button>
        )
      }
    >
      <div
        ref={logContainerRef}
        onScroll={handleScroll}
        style={{
          height: height,
          overflowY: 'auto',
          backgroundColor: '#1a1a1a',
          border: '1px solid #404040',
          borderRadius: '6px',
          padding: '12px',
          fontFamily: 'Consolas, Monaco, "Courier New", monospace',
          fontSize: '13px',
          lineHeight: '1.5',
          color: '#e5e5e5'
        }}
      >
        {displayLogs.length === 0 ? (
          <div style={{ color: '#666', fontStyle: 'italic' }}>
            等待日志输出...
          </div>
        ) : (
          displayLogs.map((log, index) => (
            <div key={index} style={{ marginBottom: '2px' }}>
              <span style={{ color: '#888' }}>[{new Date().toLocaleTimeString()}]</span>
              <span style={{ marginLeft: '8px' }}>{log}</span>
            </div>
          ))
        )}
      </div>
    </Card>
  );
};

export default LogViewer; 